package com.pj.common.exception

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import org.json.JSONException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

enum class ERROR(private val code: Int, private val err: String) {

    /**
     * 未知错误
     */
    UNKNOWN(1000, "客户端发生异常"),

    /**
     * 解析错误
     */
    PARSE_ERROR(1001, "数据解析错误"),

    /**
     * 网络错误
     */
    NETWORK_ERROR(1002, "网络不可用"),

    /**
     * 请求错误
     */
    HTTP_ERROR(1003, "网络请求失败"),

    /**
     * 请求错误
     */
    LOGIN_ERROR(403, "登录已过期，请重新登录"),

    /**
     * 连接错误
     */
    CONNECT_ERROR(1004, "网络连接失败"),


    /**
     * 证书出错
     */
    SSL_ERROR(1005, "证书出错"),

    /**
     * 连接超时
     */
    TIMEOUT_ERROR(1006, "网络连接超时");

    fun getValue(): String {
        return err
    }

    fun getKey(): Int {
        return code
    }

}

object HttpExceptionHander {
    fun handleException(e: Throwable): HttpResponseException {
        return if (e is JsonParseException
            || e is JSONException
            || e is ParseException || e is MalformedJsonException
        ) {
            HttpResponseException(ERROR.PARSE_ERROR.getKey(),ERROR.PARSE_ERROR.getValue(),e.cause)
        } else if (e is ConnectException || e is SocketException) {
            HttpResponseException(ERROR.CONNECT_ERROR.getKey(),ERROR.CONNECT_ERROR.getValue(),e.cause)
        } else if (e is SSLException) {
            HttpResponseException(ERROR.SSL_ERROR.getKey(),ERROR.SSL_ERROR.getValue(),e.cause)
        } else if (e is SocketTimeoutException) {
            HttpResponseException(ERROR.TIMEOUT_ERROR.getKey(),ERROR.TIMEOUT_ERROR.getValue(),e.cause)
        } else if (e is UnknownHostException) {
            HttpResponseException(ERROR.NETWORK_ERROR.getKey(),ERROR.NETWORK_ERROR.getValue(),e.cause)
        } else {
            HttpResponseException(ERROR.UNKNOWN.getKey(),ERROR.UNKNOWN.getValue(),e.cause)
        }

    }

}